/**
 * @author kobe
 * @date   16/06/08
 */
import {
    shopping
} from "../const/shopping";
import {
    prefix
} from "../const/prefix";
import {
    authModules
} from "../const/authModules";
import {
    ORDER_LIST
} from "../const/shopping-order";
import TipNum from "../components/TipNum";
import {dev} from "../const/dev";


(function (lf, r) {
    var RC = r.createClass,
        doAction = lf.bridgeJs.doAction,
        viewCode = lf.finger.viewCode,
        ajax = lf.utils.ajax,
        openNativeView = lf.bridgeJs.openNativeView;
    
    const NATIVE = 'native',
        H5 = 'h5',
        PAGE = {
            shoppingCart: 'shopping-cart.html',
            pendingOrder: 'shopping-order-list.html?flag=' + ORDER_LIST.PENDING,
            shippingOrder: 'shopping-order-list.html?flag=' + ORDER_LIST.SHIPPING,
            refundOrder: 'shopping-order-list.html?flag=' + ORDER_LIST.REFUND,
            unevaluatedOrder: 'shopping-order-list.html?flag=' + ORDER_LIST.UNEVALUATED,
            allOrder: 'shopping-order-list.html',
            addressManage: 'shopping-address-manage.html',
        };
    
    
    var setChoose = [
        //生产暂时隐藏
        {
            icon: '-quanbujiabandan', //不显示icon
            iconType: 'alifont',
            text: '全部订单',
            type: H5,
            url: PAGE.allOrder,
        },
        {
            text: '商家中心',
            type: H5, //跳5
            url:'store-index.html',
           // url: 'store-center.html',//没做之前的链接
        },
        {
            text: '地址管理',
            type: H5, //跳5
            url: PAGE.addressManage,
        },
        {
            text: '购物车',
            type: H5, //跳5
            url: PAGE.shoppingCart,
        },
        lf.prod ? '' : {
            text: '我的约',
            type: H5, //跳5
            url: '',
        },
        {
            text: '预警消息',
            type: H5, //跳5
            url: 'finger-early-list.html',
        },
        {
            text: '通讯录',
            addClass: 'margin-top',
            type: NATIVE, //跳native
            viewCode: viewCode.addressBook,
        },
        {
            text: '房屋住户',
            display: 'residents-hide',
            url: 'finger-me-residents.html',
            type: H5, //跳h5
        },
        // {
        //     addClass: 'margin-top',
        //     text: '健康数据',
        //     type: H5, //跳5
        //     url: 'finger-healthy-data.html',
        // },
        // lf.prod ? '' : {
        //     text: '设备状态',
        //     type: H5, //跳5
        //     url: 'finger-dev-state.html',
        // },
        lf.prod ? '' : {
            text: '健康服务',
            type: H5, //跳5
            url: 'finger-health-service.html',
        },
        {
            text: '开门位置管理',
            type: H5, //跳5
            url: 'finger-me-open-door.html',
        },
        {
            text: '设置',
            addClass: 'margin-top',
            type: NATIVE, //跳native
            viewCode: viewCode.meSetting,
        },
        // {
        //     icon: 'feedback',
        //     text: '用户反馈',
        //     url: 'finger-me-feedback.html',
        //     type: H5, //跳h5
        // },
    ];
    
    let orderQueryItems = [{
        icon: 'alifont-daifukuan',
        iconType: 'alifont',
        text: '待付款',
        url: PAGE.pendingOrder,
        numPrefix: 'pending',
        title: '',
    }, {
        icon: 'alifont-daishouhuo',
        iconType: 'alifont',
        text: '待收货',
        url: PAGE.shippingOrder,
        numPrefix: 'shipping',
        title: '',
    }, {
        icon: 'alifont-daipingjia',
        iconType: 'alifont',
        text: '待评价',
        numPrefix: 'notEvaluated',
        url: PAGE.unevaluatedOrder,
        title: '',
    },
        // {
        //     icon: 'alifont-p-return',
        //     iconType: 'alifont',
        //     text: '退款/售后',
        //     url: PAGE.refundOrder,
        //     numPrefix: 'refund',
        //     title: '',
        // },
    ];
    
    var Header = RC({
        componentDidMount: function () {
            var toMeProfile = r.findDOMNode(this.refs.toMeProfile);
            $(toMeProfile).on('tap', function () {
                doAction('finger-me-profile.html', '个人资料')
            })
        },
        render: function () {
            var user = this.props.user || {};
            return (
                <header className="header mui-table-view mui-table-view-chevron">
                    <a href="javascript:;" className="mui-navigate-right choose-line" id="toMeProfile"
                       ref="toMeProfile">
                        <div className="header-info">
                            <div className="avatar">
                                <img src={user.avatarUrl || '../public/images/finger/me-head.png'}/>
                            </div>
                            <p className="name">{user.nickName || (user.custLoginVo && user.custLoginVo.nickName) || user.name || (user.customer && user.customer.realName)}</p>
                        </div>
                    </a>
                </header>
            )
        }
        
    });
    
    /**
     * props
     *  user
     *  userType
     *  info
     *
     *  cartNum
     *  pendingNum
     *  shippingNum
     *  refundNum
     *  notEvaluatedNum
     */
    var LinkBox = RC({
        getInitialState() {
            return {
                tipNum: 0,
            }
        },
        clickFn: function () {
            
            var info = this.props.info,
                url = info.url,
                title = info.text,
                type = info.type,
                viewCode = info.viewCode,
                env = lf.utils.getEnv(),
                systemFlag = lf.utils.getSys(),
                ua = navigator.userAgent;
            
            if (env == 'app' && systemFlag == 'IOS' && ua.indexOf('Version') == -1) {
                openNativeView(viewCode);
            } else {
                if (type == NATIVE) {
                    openNativeView(viewCode);
                } else {
                    doAction(url, title);
                }
            }
        },
        componentDidMount: function () {
            r.findDOMNode(this.refs.list).addEventListener('tap', function () {
                this.clickFn();
            }.bind(this))
        },
        componentWillReceiveProps(nextProps) {
            let url = this.props.info.url || '';
            
            //设置tipNum
            if (url.indexOf(PAGE.shoppingCart) > -1 && nextProps.cartNum != this.state.tipNum) {
                this.setState({
                    tipNum: nextProps.cartNum
                });
            }
        },
        render: function () {
            let isProperty = this.props.isProperty;
            
            let info = this.props.info,
                userType = this.props.user && this.props.user.householdType || this.props.loginUser.householdType,
            //待付款等。。。
                items = info.url == PAGE.allOrder ?
                    orderQueryItems.map(data => {
                        return <a href="javascript:;" className="flex-item flex col"
                                  onTouchEnd={() => lf.appJs.doAction(data.url, data.title || data.text)}>
                            <i className={data.iconType + ' ' + data.icon}></i>
                            <span className="text">{data.text}</span>
                            <TipNum num={this.props[data.numPrefix + 'Num']}/>
                        </a>
                    }) : '';
            
            if (info.url == PAGE.allOrder) {
                return (
                    <div>
                        <li className={"mui-table-view-cell " + (info.addClass  || '')} ref="list">
                            <a href="javascript:;" className="mui-navigate-right">
                                <span className="text">{info.text}</span>
                                <TipNum num={this.state.tipNum}/>
                            </a>
                        </li>
                        <div className="order-query-items flex border-bottom">
                            {items}
                        </div>
                    </div>
                )
            } else if (!isProperty && info.text == '房屋住户' || !isProperty && info.text == '开门位置管理') {
                return <li ref="list"/>;
            }
            //else if (!this.props.loginUser.userId && info.text == '通讯录') {
            //    return <li ref="list"/>;
            //}
            else if (!(userType == 2 && info.display == 'residents-hide')) {
                if (!info.text) return <li ref="list"/>;
                return (
                    <li className={"mui-table-view-cell " + (info.addClass  || '')} ref="list">
                        <a href="javascript:;" className="mui-navigate-right">
                            <span className="text">{info.text}</span>
                            <TipNum num={this.state.tipNum}/>
                        </a>
                    </li>
                )
            } else {
                return null;
            }
        }
    });
    
    /**
     * props
     *  user
     */
    var Body = RC({
        getInitialState: function () {
            return {
                user: {},//update by user's phone data
                isProperty: false,
                loginUser: {},//这个才是真正的user
                // userType: '2', //为了避免闪现问题 默认开始时候登录为住户
                cartNum: '',
                pendingNum: '',
                shippingNum: '',
                refundNum: '',
                notEvaluatedNum: '',
            }
        },
        updateUser(user) {
            var me = this;

            ajax({
                type: "get",
                url: prefix.basic + lf.finger.api.user.getCustByGlobalId,
                data: {
                    custGlobalId: user.globalId || (user.custLoginVo && user.custLoginVo.globalId)
                },
                success: function (data) {
                    console.log(data.data);
                    //成功
                    if (data.code == '200') {
                        var data = data.data;
                        try {
                            me.setState({
                                user: data
                            });
                        } catch (e) {
                            console.log(e);
                        }
                    } else {
                        alert(data.desc);
                    }
                }
            });
        },
        getCartNum(user) {
            ajax({
                url: shopping.api.prefix + shopping.api.cart.getGoodsNum,
                data: {
                    custGlobalId: user.globalId || (user.custLoginVo && user.custLoginVo.globalId),
                }
            }, null, data => {
                try {
                    this.setState({
                        cartNum: data
                    })
                } catch (e) {
                    console.log(e);
                }
            });
        },
        /**
         * 待付款
         * 待收货
         * 待退款
         */
        getOrderNum(user) {
            ajax({
                url: shopping.api.prefix + shopping.api.order.count,
                data: {
                    custGlobalId: user.globalId || (user.custLoginVo && user.custLoginVo.globalId),
                }
            }, null, data => {
                try {
                    this.setState({
                        pendingNum: data.pendingNum,
                        shippingNum: data.shippedNum,
                        refundNum: data.refundNum,
                        notEvaluatedNum: data.notEvaluatedNum,
                    })
                } catch (e) {
                    console.log(e);
                }
            });
        },
        componentWillMount: function () {
            
            var me = this;
            
            lf.appJs.getUser(function (user) {
                console.log(user);
                user.custLoginVo && user.custLoginVo.authModules.map((type, i) => {
                    if (type == authModules.module.property) {
                        me.setState({
                            isProperty: true,
                            loginUser: user,
                        })
                    }
                })
                me.updateUser(user);
                me.getCartNum(user);
                me.getOrderNum(user);
            });
            
            lf.appJs.refresh(user => {
                console.log(user)
                user.custLoginVo && user.custLoginVo.authModules.map((type, i) => {
                    if (type == authModules.module.property) {
                        me.setState({
                            isProperty: true,
                            loginUser: user,
                        })
                    }
                })
                me.updateUser(user);
                me.getCartNum(user);
                me.getOrderNum(user);
            });
        },
        render: function () {
            var link = setChoose.map(info => {
                return (
                    <LinkBox info={info} user={this.state.user}
                             loginUser={this.state.loginUser}
                             isProperty={this.state.isProperty}
                             cartNum={this.state.cartNum}
                             pendingNum={this.state.pendingNum}
                             shippingNum={this.state.shippingNum}
                             refundNum={this.state.refundNum}
                             notEvaluatedNum={this.state.notEvaluatedNum}/>
                )
            });
            return (
                <div className="my-index">
                    <Header user={this.state.user}/>
                    <ul className="mui-table-view mui-table-view-chevron choose-link">
                        {link}
                    </ul>
                </div>
            );
        }
    });
    
    r.render(
        <Body/>,
        document.getElementById('root'),
        function () {
            $('#root').css({
                'background-color': '#ededed',
                'margin-bottom': '.3rem' //与底部撑开
            });
        }
    )
})(liefeng, React)